package com.lfc.myframe.base

import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import androidx.annotation.Nullable
import androidx.core.content.ContextCompat
import androidx.viewbinding.ViewBinding
import com.flyco.animation.BounceEnter.BounceEnter
import com.flyco.animation.SlideExit.SlideBottomExit
import com.gyf.immersionbar.ImmersionBar
import com.gyf.immersionbar.components.ImmersionFragment
import com.lfc.myframe.R
import com.lfc.myframe.event.EBParams
import com.lfc.myframe.utils.DynamicTimeFormat
import com.lfc.myframe.utils.LoadingUtil
import com.mdchina.juhai.utils.ToastUtils
import com.mdchina.juhai.utils.ToastUtils.Companion.hideToask

import com.mdchina.thelifeorder.share.MessageEvent
import com.scwang.smart.refresh.footer.BallPulseFooter
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.constant.SpinnerStyle
import com.tamsiree.rxkit.TLog
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import java.text.SimpleDateFormat
import java.util.*

abstract class BaseFg<VB : ViewBinding> : ImmersionFragment(),
    View.OnClickListener {

    /**
     * ViewBinding
     */
    private var _binding: ViewBinding? = null
    abstract val bindingInflater: (LayoutInflater, ViewGroup?, Boolean) -> VB

    @Suppress("UNCHECKED_CAST")
    protected val binding: VB
        get() = _binding as VB

    companion object {


    }

    /**
     * 视图是否加载完毕
     */
    private var isViewPrepare = false

    /**
     * 数据是否加载过了
     */
    private var hasLoadData = false

    /**
     * 初始化 View
     */
    abstract fun initView(view: View)

    /**
     * 懒加载
     */
    abstract fun lazyLoad()

    /**
     * 是否使用 EventBus
     */
    open fun useEventBus(): Boolean = true

    /**
     * 开始请求
     */
    open fun ReGetData() {}

    /**
     * 无网状态—>有网状态 的自动重连操作，子类可重写该方法
     */
    open fun doReConnected() {
        ReGetData()
    }


    /**
     * 上下文context
     */
    var baseContext: Activity = Activity()
    var mImmersionBar: ImmersionBar? = null

    /**
     * 分页加载页数
     */
    var pageNum = 1

    /**
     *  网络是否可用
     *
     */
    var ISNetWork = false
    var mClassicsHeader: ClassicsHeader? = null

    //    public ClassicsFooter mClassicsFooter;
    var mClassicsFooter: BallPulseFooter? = null
    var DialogIn = BounceEnter()
    var DialogOut = SlideBottomExit()

    private var imm: InputMethodManager? = null


    override fun initImmersionBar() {
    }

    override fun onViewCreated(view: View, @Nullable savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        baseContext = requireActivity()
        if (useEventBus()) {
            EventBus.getDefault().register(this)
        }
        isViewPrepare = true
        initRefresh()

        initView(view)
        lazyLoadDataIfPrepared()
    }

    private fun initRefresh() {
        initSmartRefresh()
        initSmartRefreshValue()
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        _binding = bindingInflater.invoke(inflater, container, false)
        return requireNotNull(_binding).root
//        return inflater.inflate(provideLayoutId(), null)
    }


    private fun initSmartRefresh() {

        mClassicsHeader = ClassicsHeader(baseContext)
        //        mClassicsFooter = new ClassicsFooter(baseContext);
        mClassicsFooter = BallPulseFooter(baseContext)
        val deta = Random().nextInt(7 * 24 * 60 * 60 * 1000)
        mClassicsHeader?.setLastUpdateTime(Date(System.currentTimeMillis() - deta))
        mClassicsHeader?.setTimeFormat(SimpleDateFormat("更新于 MM-dd HH:mm", Locale.CHINA))
        mClassicsHeader?.setTimeFormat(DynamicTimeFormat("更新于 %s"))
        mClassicsHeader?.setEnableLastTime(false)
        mClassicsHeader?.spinnerStyle = SpinnerStyle.Translate
        //        mClassicsHeader.setAccentColor(getResources().getColor(R.color.base_text));//设置强调颜色
        mClassicsHeader?.setPrimaryColor(
            ContextCompat.getColor(
                baseContext,
                R.color.StatusColor0
            )
        )//设置主题颜色

        mClassicsFooter?.setAnimatingColor(
            ContextCompat.getColor(
                baseContext,
                R.color.StatusColor0
            )
        )//设置
        mClassicsFooter?.setNormalColor(ContextCompat.getColor(baseContext, R.color.black))//设置 颜色


    }

    private fun initSmartRefreshValue() {
        ClassicsHeader.REFRESH_HEADER_PULLING = getString(R.string.srl_header_pulling);//"下拉可以刷新";
        ClassicsHeader.REFRESH_HEADER_REFRESHING =
            getString(R.string.srl_header_refreshing);//"正在刷新...";
        ClassicsHeader.REFRESH_HEADER_LOADING = getString(R.string.srl_header_loading);//"正在加载...";
        ClassicsHeader.REFRESH_HEADER_RELEASE = getString(R.string.srl_header_release);//"释放立即刷新";
        ClassicsHeader.REFRESH_HEADER_FINISH = getString(R.string.srl_header_finish);//"刷新完成";
        ClassicsHeader.REFRESH_HEADER_FAILED = getString(R.string.srl_header_failed);//"刷新失败";
        ClassicsHeader.REFRESH_HEADER_UPDATE =
            getString(R.string.srl_header_update);//"上次更新 M-d HH:mm";
        ClassicsHeader.REFRESH_HEADER_UPDATE =
            getString(R.string.srl_header_update);//"'Last update' M-d HH:mm";
        ClassicsHeader.REFRESH_HEADER_SECONDARY =
            getString(R.string.srl_header_secondary);//"释放进入二楼"

        ClassicsFooter.REFRESH_FOOTER_PULLING = getString(R.string.srl_footer_pulling);//"上拉加载更多";
        ClassicsFooter.REFRESH_FOOTER_RELEASE = getString(R.string.srl_footer_release);//"释放立即加载";
        ClassicsFooter.REFRESH_FOOTER_LOADING = getString(R.string.srl_footer_loading);//"正在刷新...";
        ClassicsFooter.REFRESH_FOOTER_REFRESHING =
            getString(R.string.srl_footer_refreshing);//"正在加载...";
        ClassicsFooter.REFRESH_FOOTER_FINISH = getString(R.string.srl_footer_finish);//"加载完成";
        ClassicsFooter.REFRESH_FOOTER_FAILED = getString(R.string.srl_footer_failed);//"加载失败";
        ClassicsFooter.REFRESH_FOOTER_NOTHING = getString(R.string.srl_footer_nothing);//"全部加载完成";

    }

    open fun getData(isLoad: Boolean = false) {

    }

    /**
     * 扩展 吐司
     */
    fun Context.showToast(strMsg: String?) {
        if (strMsg.isNullOrBlank()) {
            return
        } else {
//            Toast.makeText(this, strMsg, Toast.LENGTH_SHORT).show()
            ToastUtils.showToask(baseContext, strMsg)
        }
    }

    protected fun provideLayoutId(): Int {
        return 0
    }


    override fun onClick(v: View?) {
    }


    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (isVisibleToUser) {
            lazyLoadDataIfPrepared()
        }
    }

    private fun lazyLoadDataIfPrepared() {
        if (userVisibleHint && isViewPrepare && !hasLoadData) {
            lazyLoad()
            hasLoadData = true
        }
    }

    /**
     * 加载中
     */
    fun show_Loading() {
        LoadingUtil.showLoading(baseContext, "加载中...")
//        showDialog()
    }

    /**
     * 取消加载
     */
    fun hide_Loading() {
        LoadingUtil.dismissLoading()
//        hideDialog()
    }

    /**
     * eventbus
     */
    @Subscribe
//    (sticky = true)
    //    @Subscribe(threadMode = ThreadMode.POSTING)
    //    @Subscribe(threadMode = ThreadMode.MAIN)
    open fun onEventBus(message: MessageEvent) {
        val str_name = message.name
        TLog.d("收到 回调消息" + str_name)
        if (TextUtils.isEmpty(str_name)) {
            return
        }
        if (TextUtils.equals(str_name, EBParams.EB_NetConnectState)) {
            if (message.type == 1) {
                TLog.e("FG 有网了！ ${message.password01}")
                doReConnected()
            } else {
                TLog.e("FG断网了！ ")
//                checkNetwork(false)
            }

        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (useEventBus()) {
            EventBus.getDefault().unregister(this)
        }
        hideToask()
        _binding = null
//        isCreated = false
//        hasLoaded = false
    }

}
